package br.com.fogas.medicao.business;

import br.com.fogas.database.entidade.Config;
import br.com.fogas.medicao.R;
import br.com.fogas.utils.dialog.DialogAlert;
import br.com.fogas.utils.task.ServiceTask;
import br.com.fogas.utils.task.ServiceTaskBusiness;
import br.com.fogas.medicao.activity.helper.ConfiguracaoHelper;
import br.com.fogas.medicao.application.ApplicationFogas;
import br.com.fogas.utils.StringUtility;

public class ConfigurationBusiness implements ServiceTaskBusiness {
	
	private ConfiguracaoHelper helper;

	public ConfigurationBusiness(ConfiguracaoHelper helper) {
		this.helper = helper;
	}

	@Override
	public void start(ServiceTask serviceTask) {
		try {
			boolean nfeOnline = helper.getCbxConfigSincNfe().isChecked();
			Integer tentativasQrCode = Integer.valueOf(helper.getEtConfigTentativasLeiQrcode().getText().toString());
			Integer tempoNfeOnline = Integer.valueOf(helper.getEtConfigTempoEsperaAutNfe().getText().toString());
			Integer tempoProcSync = Integer.valueOf(helper.getEtConfigTempoProcSync().getText().toString());
			String novaSenhaAdm = helper.getEtConfigSenhaAdm().getText().toString().trim();
			
			Config config = helper.getDatabase().getConfig().queryForId(1);
			config.setCs_sync_nfe_online(nfeOnline);
			config.setNb_tentativas_leitura_qrcode(tentativasQrCode);
			config.setNb_tempo_espera_aut_nfe(tempoNfeOnline);
			config.setNb_tempo_processamento_sync(tempoProcSync);
			if(StringUtility.isNotEmpty(novaSenhaAdm)) {
				config.setTx_senha_adm(novaSenhaAdm);
			}
			helper.getDatabase().getConfig().update(config);
			ApplicationFogas.getInstance().setConfiguracao();
			
			helper.atualizarCampos();
			
			DialogAlert.newInstance()
			.setTitle(R.string.dialog_title_alert)
			.setMessage(R.string.dialog_config_sucesso_atualizar)
			.showDialog(helper.getActivity().getSupportFragmentManager());
		} catch (Exception e) {
			DialogAlert.newInstance()
			.setTitle(R.string.dialog_title_alert)
			.setMessage(R.string.dialog_config_error_atualizar)
			.showDialog(helper.getActivity().getSupportFragmentManager());
		}
	}
}